package zipdemo
{
	import com.probertson.utils.GZIPBytesEncoder;
	
	import flash.display.Sprite;
	import flash.errors.IllegalOperationError;
	import flash.events.Event;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.utils.ByteArray;
	
	import nochump.util.zip.*;
	
	public class ZipDemo extends Sprite
	{
		private var loader:URLLoader;
		private var isZip:Boolean = false;
		
		public function ZipDemo()
		{
			loader = new URLLoader();
			loader.dataFormat = URLLoaderDataFormat.BINARY;
			loader.addEventListener(Event.COMPLETE, completeHandler);
			//var request:URLRequest = new URLRequest("c28160bdc6a4950bac156f1604e638a3.zip");
			var request:URLRequest;
			if(isZip)
			{
				request = new URLRequest("Encode_Address.zip");
			}
			else if(!isZip)
			{
				//http://blog.skinkers.com/2010/09/02/adding-gzip-support-for-flexair-httpservice-urlloader/
				request = new URLRequest("zipdemo/example.gz");
			}
			loader.load(request);
		}
		
		private function completeHandler(evt:Event):void
		{
			if(!isZip)
			{
				var byteArray:ByteArray = loader.data as ByteArray;
	            try
	            {
		                var encoder:GZIPBytesEncoder = new GZIPBytesEncoder();
		                loader.data = encoder.uncompressToByteArray(byteArray).toString();
						trace(loader.data);
	           }
	           catch(error:IllegalOperationError)
	           {
		               //Not gzip compressed - assume utf8
		               byteArray.position = 0;//reset to start of bytearray
		               loader.data = byteArray.readUTFBytes(byteArray.length);
					   trace(loader.data);
	           }
			}
			else if(isZip)
			{
				var t0:Number = 0;
				var zipFile:ZipFile = new ZipFile(loader.data);
				for(var i:int = 0; i < zipFile.entries.length; i++) {
					var entry:ZipEntry = zipFile.entries[i];
					trace(entry.name);
					// extract the entry's data from the zip
					t0 = new Date().getTime();
					var data:ByteArray = zipFile.getInput(entry);
					trace(new Date().getTime() - t0);
					trace(data.toString());
				}
			}
		}
	}
}